﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace CopyCameraFiles
{
    public class FileCopier
    {

        public event EventHandler<FileCopierEventArgs> FileCopiedEvent;
        public event EventHandler<ErrorEventArgs> ErrorEvent;

       protected virtual void OnFileCopiedEvent(FileCopierEventArgs e)
        {
            EventHandler<FileCopierEventArgs> handler = FileCopiedEvent;
            if (handler != null) 
                handler(this, e);
        }

        protected virtual void OnErrorEvent(ErrorEventArgs e)
        {
            EventHandler<ErrorEventArgs> handler = ErrorEvent;
            if (handler != null)
                handler(this, e);
        }

        public int Copy(IEnumerable<FileInfo> sourceFiles, DirectoryInfo destinationRootFolder)
        {
            if (sourceFiles == null) throw new NullReferenceException("sourceFiles is null.");
            if (destinationRootFolder == null) throw new NullReferenceException("destinationRoolFolder is null.");

            var copyCounter = 0;
            sourceFiles.OrderBy(f => f.CreationTime);
            foreach (var fileInfo in sourceFiles)
            {
                var fileName = fileInfo.Name;
                var creationDate = fileInfo.LastWriteTime.Date.ToString("yyyy-MM-dd");
                var destinationFolder = Path.Combine(destinationRootFolder.ToString(), creationDate.ToString());
                var folderResult = FolderExist(creationDate, destinationRootFolder);
                if (folderResult == null)
                    Directory.CreateDirectory(destinationFolder);
                else
                    destinationFolder = folderResult; //this is the renamed folder
                try
                {
                    var destinationPath = Path.Combine(destinationFolder, fileName);
                    if (!File.Exists(destinationPath))
                    { 
                        fileInfo.CopyTo(destinationPath);
                        OnFileCopiedEvent(new FileCopierEventArgs("Copying file",fileInfo));
                        copyCounter++;
                    }
                }
                catch (DirectoryNotFoundException)
                {
                    throw;
                }   
            }
            return copyCounter;
        }

        private string FolderExist(string match, DirectoryInfo destinationFolder)
        {
            foreach (var folder in destinationFolder.GetDirectories("*" + match + "*",SearchOption.TopDirectoryOnly))
	        {
		        return folder.FullName;
	        }
            return null;
            
        }
    }
}
